package bp.web;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Per-request user context based on ThreadLocal to avoid static cross-request state.
 */
public final class UserContextHolder {
    private static final ThreadLocal<Map<String, String>> CTX = new ThreadLocal<>();
    private static final ThreadLocal<String> REQ_TOKEN = new ThreadLocal<>();

    private UserContextHolder() {}

    public static void set(Map<String, String> ctx) {
        if (ctx == null) {
            CTX.remove();
        } else {
            CTX.set(ctx);
        }
    }

    public static Map<String, String> get() {
        Map<String, String> map = CTX.get();
        return map == null ? null : map;
    }

    public static boolean has() {
        return CTX.get() != null;
    }

    public static void clear() {
        CTX.remove();
        REQ_TOKEN.remove();
    }

    // Per-request chosen token override to stabilize writes/reads.
    public static void setRequestToken(String token) {
        if (token == null || token.isEmpty()) {
            REQ_TOKEN.remove();
        } else {
            REQ_TOKEN.set(token);
        }
    }
    public static String getRequestToken() { return REQ_TOKEN.get(); }
}
